package com.service.tools.componets;

import jakarta.servlet.Filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Component
@Order(1)
public class TokenFilter implements Filter {
    
    private static final List<String> EXCLUDE_PATHS = Arrays.asList("/login", "/register");
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        String path = httpRequest.getRequestURI();
        
        // 检查是否为排除路径
        if (EXCLUDE_PATHS.stream().anyMatch(path::startsWith)) {
            chain.doFilter(request, response);
            return;
        }
        
        // 检查方法上是否有@NoAuth注解
        if (isNoAuthAnnotationPresent(httpRequest)) {
            chain.doFilter(request, response);
            return;
        }
        
        // 验证token
        String token = httpRequest.getHeader("Authorization");
        if (token == null || !validateToken(token)) {
            httpResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
            return;
        }
        
        chain.doFilter(request, response);
    }
    
    private boolean isNoAuthAnnotationPresent(HttpServletRequest request) {
        // 通过反射获取对应的方法和类上的注解
        return false;
    }
    
    private boolean validateToken(String token) {
        // 实现token验证逻辑
        return true;
    }
}
